/**
 * 热门实习页面JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initInternshipsPage();
});

/**
 * 初始化实习页面
 */
function initInternshipsPage() {
    // 初始化刷新功能
    initPullToRefresh();
    
    // 初始化筛选选项
    initFilterOptions();
    
    // 初始化排序选项
    initSortOptions();
    
    // 初始化筛选弹窗
    initFilterModal();
    
    // 初始化搜索功能
    initSearch();
    
    // 加载实习职位数据
    loadInternships();
    
    // 处理图片加载错误
    handleImageErrors();
}

/**
 * 初始化下拉刷新功能
 */
function initPullToRefresh() {
    let startY = 0;
    let diffY = 0;
    const refreshIndicator = document.querySelector('.refresh-indicator');
    const refreshIcon = document.querySelector('.refresh-icon');
    const refreshText = document.querySelector('.refresh-text');
    
    document.addEventListener('touchstart', function(e) {
        if (window.scrollY === 0) {
            startY = e.touches[0].clientY;
        }
    });
    
    document.addEventListener('touchmove', function(e) {
        if (startY > 0 && window.scrollY === 0) {
            diffY = e.touches[0].clientY - startY;
            if (diffY > 0) {
                const pullDistance = Math.min(diffY * 0.5, 60);
                refreshIndicator.classList.add('visible');
                refreshIndicator.style.marginTop = (pullDistance - 60) + 'px';
                
                // 更新下拉提示
                if (pullDistance > 50) {
                    refreshText.textContent = '释放刷新';
                    refreshIcon.style.transform = 'rotate(180deg)';
                } else {
                    refreshText.textContent = '下拉刷新';
                    refreshIcon.style.transform = 'rotate(0deg)';
                }
                
                e.preventDefault();
            }
        }
    });
    
    document.addEventListener('touchend', function() {
        if (diffY > 0 && window.scrollY === 0) {
            if (diffY * 0.5 > 50) {
                // 触发刷新
                refreshIndicator.classList.add('refreshing');
                refreshIndicator.style.marginTop = '0';
                refreshText.textContent = '正在刷新...';
                refreshIcon.style.transform = 'rotate(0deg)';
                
                // 模拟加载新数据
                loadInternships(true);
                
                // 2秒后恢复
                setTimeout(function() {
                    refreshIndicator.classList.remove('refreshing');
                    refreshIndicator.classList.remove('visible');
                    refreshIndicator.style.marginTop = '-60px';
                }, 2000);
            } else {
                // 取消刷新
                refreshIndicator.classList.remove('visible');
                refreshIndicator.style.marginTop = '-60px';
            }
            
            startY = 0;
            diffY = 0;
        }
    });
}

/**
 * 初始化筛选选项
 */
function initFilterOptions() {
    const filterOptions = document.querySelectorAll('.filter-option');
    
    filterOptions.forEach(option => {
        option.addEventListener('click', function() {
            // 如果点击的是"更多筛选"选项，显示弹窗
            if (this.dataset.filter === 'more') {
                document.querySelector('.filter-modal').classList.add('open');
                return;
            }
            
            // 切换选中状态
            this.classList.toggle('active');
            
            // 重新加载数据
            loadInternships();
        });
    });
}

/**
 * 初始化排序选项
 */
function initSortOptions() {
    const sortOptions = document.querySelectorAll('.sort-option');
    
    sortOptions.forEach(option => {
        option.addEventListener('click', function() {
            // 清除所有选项的选中状态
            sortOptions.forEach(opt => opt.classList.remove('active'));
            
            // 设置当前选项为选中状态
            this.classList.add('active');
            
            // 重新加载数据
            loadInternships();
        });
    });
}

/**
 * 初始化筛选弹窗
 */
function initFilterModal() {
    const filterModal = document.querySelector('.filter-modal');
    const closeBtn = document.querySelector('.close-modal');
    const resetBtn = document.querySelector('.reset-btn');
    const applyBtn = document.querySelector('.apply-btn');
    
    // 关闭按钮
    closeBtn.addEventListener('click', function() {
        filterModal.classList.remove('open');
    });
    
    // 重置按钮
    resetBtn.addEventListener('click', function() {
        const checkboxes = filterModal.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
        });
    });
    
    // 确定按钮
    applyBtn.addEventListener('click', function() {
        filterModal.classList.remove('open');
        // 应用筛选条件并重新加载数据
        loadInternships();
    });
}

/**
 * 初始化搜索功能
 */
function initSearch() {
    const searchInput = document.querySelector('.search-input');
    let timer;
    
    searchInput.addEventListener('input', function() {
        clearTimeout(timer);
        timer = setTimeout(function() {
            loadInternships();
        }, 500);
    });
}

/**
 * 加载实习职位数据
 * @param {boolean} isRefresh - 是否是下拉刷新触发的加载
 */
function loadInternships(isRefresh = false) {
    // 显示加载中
    showLoading(true);
    
    // 隐藏无结果提示
    document.querySelector('.no-results').classList.remove('visible');
    
    // 清空列表（如果不是刷新）
    if (!isRefresh) {
        document.querySelector('.internships-list').innerHTML = '';
    }
    
    // 获取搜索关键词
    const searchTerm = document.querySelector('.search-input').value.trim();
    
    // 获取选中的筛选选项
    const activeFilters = Array.from(document.querySelectorAll('.filter-option.active')).map(
        option => option.dataset.filter
    );
    
    // 获取选中的排序选项
    const activeSortOption = document.querySelector('.sort-option.active').dataset.sort;
    
    // 模拟API请求延迟
    setTimeout(function() {
        // 模拟数据
        const internships = getMockInternships();
        
        // 筛选数据
        let filteredData = internships;
        
        // 根据搜索词筛选
        if (searchTerm) {
            filteredData = filteredData.filter(job => 
                job.title.toLowerCase().includes(searchTerm.toLowerCase()) || 
                job.company.toLowerCase().includes(searchTerm.toLowerCase()) ||
                job.description.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }
        
        // 根据筛选选项筛选
        if (activeFilters.length > 0) {
            filteredData = filteredData.filter(job => {
                return activeFilters.some(filter => {
                    if (filter === 'internship') return job.type === '实习';
                    if (filter === 'fulltime') return job.type === '全职';
                    if (filter === 'remote') return job.location.includes('远程');
                    if (filter === 'tech') return job.category === '技术';
                    if (filter === 'design') return job.category === '设计';
                    if (filter === 'marketing') return job.category === '市场';
                    return true;
                });
            });
        }
        
        // 根据排序选项排序
        if (activeSortOption === 'latest') {
            filteredData.sort((a, b) => new Date(b.date) - new Date(a.date));
        } else if (activeSortOption === 'salary') {
            filteredData.sort((a, b) => {
                const salaryA = parseFloat(a.salary.replace(/[^0-9.-]+/g, ''));
                const salaryB = parseFloat(b.salary.replace(/[^0-9.-]+/g, ''));
                return salaryB - salaryA;
            });
        }
        
        // 判断是否有结果
        if (filteredData.length === 0) {
            document.querySelector('.no-results').classList.add('visible');
        } else {
            // 渲染数据
            renderInternships(filteredData);
        }
        
        // 隐藏加载中
        showLoading(false);
        
        // 添加卡片动画
        animateCards();
    }, 1000);
}

/**
 * 渲染实习职位列表
 * @param {Array} internships - 实习职位数据数组
 */
function renderInternships(internships) {
    const container = document.querySelector('.internships-list');
    
    internships.forEach(job => {
        const jobCard = createJobCard(job);
        container.appendChild(jobCard);
        
        // 添加涟漪效果
        jobCard.addEventListener('click', function(e) {
            createRippleEffect(e, this);
            
            // 跳转到详情页
            setTimeout(() => {
                window.location.href = `internship-detail.html?id=${job.id}`;
            }, 300);
        });
    });
}

/**
 * 创建职位卡片元素
 * @param {Object} job - 职位数据
 * @returns {HTMLElement} - 创建的卡片元素
 */
function createJobCard(job) {
    const card = document.createElement('div');
    card.className = 'job-card';
    card.dataset.id = job.id;
    
    // 格式化日期
    const jobDate = formatDate(job.date);
    
    // 确定工作类型对应的图标
    const jobTypeIcon = job.type.includes('开发') ? 'code' : 
                        job.type.includes('产品') ? 'lightbulb' : 
                        job.type.includes('设计') ? 'palette' : 
                        job.type.includes('运营') ? 'campaign' : 
                        job.type.includes('数据') ? 'analytics' : 'business_center';
    
    card.innerHTML = `
        <div class="job-header">
            <img src="${job.logo}" alt="${job.company}" class="company-logo" loading="lazy">
        </div>
        <div class="job-content">
            <div class="job-top">
                <h3 class="job-title">${job.title}</h3>
                <span class="job-salary">${job.salary}</span>
            </div>
            <p class="company-name">${job.company}</p>
            <div class="job-middle">
                <span class="job-tag job-tag-blue">
                    <span class="job-tag-icon material-symbols-rounded">${jobTypeIcon}</span>
                    ${job.type}
                </span>
                <span class="job-tag">
                    <span class="job-tag-icon material-symbols-rounded">location_on</span>
                    ${job.location}
                </span>
                <span class="job-tag">
                    <span class="job-tag-icon material-symbols-rounded">school</span>
                    ${job.education}
                </span>
            </div>
            <p class="job-description">${job.description}</p>
            <button class="job-apply">立即申请</button>
        </div>
        <div class="job-right">
            <div class="job-type">${job.type.includes('校招') ? '校招' : '实习'}</div>
            <div class="job-date">${jobDate}</div>
        </div>
    `;
    
    return card;
}

/**
 * 处理图片加载错误
 */
function handleImageErrors() {
    document.addEventListener('error', function(e) {
        const target = e.target;
        // 检查是否是公司logo图片
        if (target.classList.contains('company-logo') && target.tagName === 'IMG') {
            // 获取公司名称用于生成特定图片
            const companyName = target.alt || 'company';
            const cardElement = target.closest('.job-card');
            const jobType = cardElement ? (cardElement.querySelector('.job-type').textContent || '') : '';
            
            // 根据工作类型选择不同的图片类别
            const imageCategory = jobType.includes('校招') ? 'company/office' : 'company/startup';
            
            // 生成随机ID确保每次都获取新图片
            const randomId = Math.floor(Math.random() * 1000);
            
            // 设置替代图片
            target.src = `https://source.unsplash.com/random/300x300/?${imageCategory}/${randomId}`;
            
            // 设置加载优先级
            target.loading = 'eager';
            
            // 添加淡入效果
            target.style.opacity = '0';
            setTimeout(() => {
                target.style.transition = 'opacity 0.3s ease';
                target.style.opacity = '1';
            }, 50);
        }
    }, true);
}

/**
 * 创建涟漪效果
 * @param {Event} e - 点击事件
 * @param {HTMLElement} element - 添加效果的元素
 */
function createRippleEffect(e, element) {
    // 检查是否已存在涟漪元素
    const rippleElements = element.getElementsByClassName('ripple');
    for (let i = 0; i < rippleElements.length; i++) {
        rippleElements[i].remove();
    }
    
    // 创建涟漪元素
    const ripple = document.createElement('span');
    ripple.className = 'ripple';
    element.appendChild(ripple);
    
    // 获取点击位置
    const rect = element.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // 设置涟漪元素的位置和尺寸
    const size = Math.max(rect.width, rect.height) * 2;
    ripple.style.width = ripple.style.height = `${size}px`;
    ripple.style.left = `${x - size / 2}px`;
    ripple.style.top = `${y - size / 2}px`;
    
    // 自动清除涟漪元素
    setTimeout(() => {
        ripple.remove();
    }, 600);
}

/**
 * 显示或隐藏加载提示
 * @param {boolean} show - 是否显示加载提示
 */
function showLoading(show) {
    const loadingSpinner = document.querySelector('.loading-spinner');
    
    if (show) {
        loadingSpinner.classList.add('visible');
    } else {
        loadingSpinner.classList.remove('visible');
    }
}

/**
 * 格式化日期
 * @param {string} dateString - 日期字符串
 * @returns {string} - 格式化后的日期字符串
 */
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = Math.abs(now - date);
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
        return '今天';
    } else if (diffDays === 1) {
        return '昨天';
    } else if (diffDays < 7) {
        return `${diffDays}天前`;
    } else if (diffDays < 30) {
        return `${Math.floor(diffDays / 7)}周前`;
    } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
}

/**
 * 为卡片添加动画效果
 */
function animateCards() {
    // 使用Intersection Observer API检测卡片是否在视口中
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = 1;
                entry.target.style.transform = 'translateY(0)';
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1 });
    
    // 观察所有卡片
    const cards = document.querySelectorAll('.job-card');
    cards.forEach((card, index) => {
        // 设置初始样式
        card.style.opacity = 0;
        card.style.transform = 'translateY(20px)';
        card.style.transition = `opacity 0.3s ease ${index * 0.05}s, transform 0.3s ease ${index * 0.05}s`;
        
        observer.observe(card);
    });
}

/**
 * 获取模拟实习职位数据
 * @returns {Array} - 模拟数据数组
 */
function getMockInternships() {
    return [
        {
            id: 1,
            title: '前端开发实习生',
            company: '腾讯科技',
            logo: 'https://source.unsplash.com/random/100x100/?tech/1',
            salary: '300-400元/天',
            type: '实习',
            location: '北京',
            education: '本科及以上',
            description: '负责公司产品的前端开发，参与产品的设计与开发，善于学习和掌握新技术，热爱互联网和新技术应用。',
            tags: ['互联网', '前端开发', '科技'],
            date: '2023-07-01'
        },
        {
            id: 2,
            title: 'UI设计实习生',
            company: '阿里巴巴',
            logo: 'https://source.unsplash.com/random/100x100/?design/2',
            salary: '350-450元/天',
            type: '实习',
            location: '杭州',
            education: '本科及以上',
            description: '负责公司产品的UI设计，参与产品体验优化，具有良好的审美能力和创新意识，熟练使用设计软件。',
            tags: ['电商', 'UI设计', '互联网'],
            date: '2023-07-02'
        },
        {
            id: 3,
            title: '数据分析实习生',
            company: '百度',
            logo: 'https://source.unsplash.com/random/100x100/?data/3',
            salary: '280-380元/天',
            type: '实习',
            location: '北京',
            education: '本科及以上',
            description: '负责公司产品数据的收集、整理和分析，撰写数据分析报告，为产品决策提供数据支持。',
            tags: ['互联网', '数据分析', '人工智能'],
            date: '2023-07-03'
        },
        {
            id: 4,
            title: '市场营销实习生',
            company: '字节跳动',
            logo: 'https://source.unsplash.com/random/100x100/?marketing/4',
            salary: '250-350元/天',
            type: '实习',
            location: '上海',
            education: '本科及以上',
            description: '负责公司产品的市场推广和营销活动策划，参与社交媒体运营，有良好的创意能力和沟通能力。',
            tags: ['互联网', '短视频', '营销'],
            date: '2023-07-04'
        },
        {
            id: 5,
            title: '后端开发实习生',
            company: '华为',
            logo: 'https://source.unsplash.com/random/100x100/?tech/5',
            salary: '400-500元/天',
            type: '实习',
            location: '深圳',
            education: '本科及以上',
            description: '负责公司产品的后端开发，参与系统架构设计和优化，具有良好的编程能力和解决问题的能力。',
            tags: ['通信', '后端开发', '5G'],
            date: '2023-07-05'
        },
        {
            id: 6,
            title: '产品经理实习生',
            company: '小米',
            logo: 'https://source.unsplash.com/random/100x100/?product/6',
            salary: '300-400元/天',
            type: '实习',
            location: '北京',
            education: '本科及以上',
            description: '负责公司产品的需求分析和功能设计，参与产品规划和用户体验优化，有良好的沟通能力和团队协作精神。',
            tags: ['智能硬件', '互联网', '产品'],
            date: '2023-07-06'
        },
        {
            id: 7,
            title: '人力资源实习生',
            company: '京东',
            logo: 'https://source.unsplash.com/random/100x100/?hr/7',
            salary: '200-300元/天',
            type: '实习',
            location: '北京',
            education: '本科及以上',
            description: '负责公司的招聘、培训和员工关系管理，参与人力资源政策制定，有良好的沟通能力和组织能力。',
            tags: ['电商', 'HR', '互联网'],
            date: '2023-07-07'
        },
        {
            id: 8,
            title: '算法工程师实习生',
            company: '网易',
            logo: 'https://source.unsplash.com/random/100x100/?algorithm/8',
            salary: '400-500元/天',
            type: '实习',
            location: '杭州',
            education: '硕士及以上',
            description: '负责公司产品的算法研发和优化，参与机器学习模型的设计和实现，具有良好的数学基础和编程能力。',
            tags: ['游戏', '算法', '机器学习'],
            date: '2023-07-08'
        },
        {
            id: 9,
            title: '运营实习生',
            company: '美团',
            logo: 'https://source.unsplash.com/random/100x100/?operation/9',
            salary: '250-350元/天',
            type: '实习',
            location: '北京',
            education: '本科及以上',
            description: '负责公司产品的运营活动策划和执行，参与用户增长策略制定，有良好的创意能力和执行力。',
            tags: ['本地生活', '互联网', '运营'],
            date: '2023-07-09'
        },
        {
            id: 10,
            title: '财务实习生',
            company: '滴滴',
            logo: 'https://source.unsplash.com/random/100x100/?finance/10',
            salary: '200-300元/天',
            type: '实习',
            location: '北京',
            education: '本科及以上',
            description: '负责公司的财务核算和分析，参与预算管理和财务报表编制，具有良好的财务专业知识和责任心。',
            tags: ['出行', '互联网', '财务'],
            date: '2023-07-10'
        },
        {
            id: 11,
            title: '安卓开发实习生',
            company: 'OPPO',
            logo: 'https://source.unsplash.com/random/100x100/?android/11',
            salary: '350-450元/天',
            type: '实习',
            location: '深圳',
            education: '本科及以上',
            description: '负责公司Android应用的开发和维护，参与功能设计和实现，具有良好的Java编程能力和Android开发经验。',
            tags: ['手机', '安卓开发', '硬件'],
            date: '2023-07-11'
        },
        {
            id: 12,
            title: 'iOS开发实习生',
            company: 'vivo',
            logo: 'https://source.unsplash.com/random/100x100/?ios/12',
            salary: '350-450元/天',
            type: '实习',
            location: '东莞',
            education: '本科及以上',
            description: '负责公司iOS应用的开发和维护，参与功能设计和实现，具有良好的Swift/Objective-C编程能力和iOS开发经验。',
            tags: ['手机', 'iOS开发', '硬件'],
            date: '2023-07-12'
        }
    ];
} 